package com.cndongtai.net;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Date;

import com.cndongtai.net.analysis.WIFIMessageFilter;
import com.cndongtai.util.ByteUtil;
import com.cndongtai.util.CRC16;

public class WIFISocketHandler implements Runnable{

	private Socket socket;
	
	public WIFISocketHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			System.out.println("有连接进入");
			InputStream in=socket.getInputStream();
//			OutputStream out=socket.getOutputStream();
		
			// 获取签到报文
			byte[] buf=new byte[1024];
			
			int length=in.read(buf);
			
			StringBuffer sb = new StringBuffer();
			for(int i=0;i<length;i++) {
				sb.append(ByteUtil.hexStringFormat(Integer.toHexString(ByteUtil.getUnsignedByte(buf[i])).toUpperCase())).append(" ");
			}
			
			System.out.println(new Date() + "WIFIreq===>" + sb.toString());
			//A2 5B 00 10 48 A1 00 00 00 01 11 11 00 00 82 B5
			
			// 判断报文头
			if(length<10) {
				System.out.println("报文不合法1");
				return;
			}
			
			// 终端ID
			String id = ByteUtil.hexStringFormat(Integer.toHexString(ByteUtil.getUnsignedByte(buf[0])).toUpperCase());
			// 功能代码
			String code =  ByteUtil.hexStringFormat(Integer.toHexString(ByteUtil.getUnsignedByte(buf[1])).toUpperCase());
			if(!"03".equals(code)&&!"04".equals(code)) {
				System.out.println("报文不合法2");
				return;
			}
			
			// 获取长度
			int msgsize = ByteUtil.getUnsignedByte(buf[2]);
			System.out.println(length+"=="+msgsize);
			// 校验报文长度
			if(length!=msgsize+5) {
				System.out.println("报文不合3");
				return;
			}
			
			// CRC16校验
			int crcReq = CRC16.calcCrc16(buf,0,47);
			int crcvalReq = Integer.parseInt(ByteUtil.hexStringFormat(Integer.toHexString(ByteUtil.getUnsignedByte(buf[48])).toUpperCase()) + ByteUtil.hexStringFormat(Integer.toHexString(ByteUtil.getUnsignedByte(buf[47])).toUpperCase()), 16);
			if(crcReq!=crcvalReq) {
				System.out.println("CRC校验失败，" + crcReq + " " + crcvalReq);
				return;
			}
			
			byte[] msg = new byte[length];
			System.arraycopy(buf, 0, msg, 0, length);
			
			try {
				WIFIMessageFilter.doMsg(msg);
			}catch(Exception e) {
				e.printStackTrace();
			}
			
			
			String panId = "WIFI"+id;
			
			WIFISocketContainer oldContainer = WIFINetController.getSocketPool().get(panId);
			if(oldContainer!=null) {
				oldContainer.stopThread();
				oldContainer.closeSocket();
			}
			
			SocketContainer container = new SocketContainer(panId,socket);
			container.start();
			
			NetController.getSocketPool().put(panId, container);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	 }
	
}
